package com.hu.bgp.client.widgets;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.Widget;
import com.hu.bgp.shared.ClientGameInstance;

public class GameInstanceTable extends HeaderedFlexTable
{
	private static final String GAMETYPE_RADIOGROUP = "gameType";
	private int rows = 1;
	private int columns = 1;
	private ClientGameInstance selection;

	public GameInstanceTable()
	{
		super();
		clear();
		this.getElement().addClassName("bgptable");
	}

	public ClientGameInstance getSelection()
	{
		return selection;
	}

	public void addGameInstanceRow(ClientGameInstance instance)
	{
		new GameInstanceRow(instance, createRow(instance));
	}

	public void clear()
	{
		super.clear();
		rows = 1;
		columns = 1;
		this.setHeaderElement(0, DOM.createDiv());
		for (Label l : createHeader())
		{
			this.setHeaderElement(columns++, l.getElement());
		}
	}

	protected class GameInstanceRow
	{
		private final ClientGameInstance instance;
		private final RadioButton rb = new RadioButton(GAMETYPE_RADIOGROUP);

		public GameInstanceRow(ClientGameInstance instance, Widget[] fields)
		{
			this.instance = instance;
			rb.addValueChangeHandler(new ValueChangeHandler<Boolean>()
			{
				public void onValueChange(ValueChangeEvent<Boolean> event)
				{
					selection = GameInstanceRow.this.instance;
				}
			});

			setWidget(rows, 0, rb);
			int rc = 1;
			for (Widget w : fields)
			{
				setWidget(rows, rc++, w);
			}
			rows++;
		}
	}

	public Label[] createHeader()
	{
		return new Label[]
		{
			new Label("Id"), new Label("State"), new Label("Players"), new Label("Start date")
		};
	}

	public Widget[] createRow(ClientGameInstance instance)
	{
		return new Widget[]
		{
			new Label(instance.getId()), new Label(instance.getState()), new Label(instance.getPlayers()), new Label(instance.getStartDate())
		};
	}
}
